import * as signalr from "@microsoft/signalr";

export default function useSignalR() {
  //连接容器
  let connection = null;

  //注册signalr
  function registerSignalR(socketUrl, url) {
    connection = new signalr.HubConnectionBuilder()
      .configureLogging(signalr.LogLevel.Error)
      .withAutomaticReconnect()
      .withUrl(socketUrl + "/" + url, {
        headers: {
          Authorization: `Bearer xxx`,
        },
      })
      .build();

    connection.start().then(() => {
      console.log("连接成功");
    });

    connection.onclose((error) => {
      // 处理连接关闭时的逻辑
      console.log("连接关闭", error);
    });

    connection.onreconnected(() => {
      console.log("重连成功");
    });
  }

  function connectionFun(name, method) {
    connection.on(name, method);
  }

  function connectionStop() {
    connection.stop();
  }

  return {
    registerSignalR,
    connectionFun,
    connectionStop,
  };
}
